package com.fhminyi.GUI;

import com.fhminyi.dao.OrderDao;
import com.fhminyi.model.Order;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class OrderManagementPanel extends JPanel {
    private JTable orderTable;
    private DefaultTableModel orderTableModel;
    private JButton deleteOrderButton;
    private JButton addOrderButton; // 添加订单按钮
    private JButton editOrderButton; // 编辑订单按钮

    public OrderManagementPanel() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createTitledBorder("订单管理"));

        orderTableModel = new DefaultTableModel();
        orderTableModel.addColumn("订单ID");
        orderTableModel.addColumn("用户ID");
        orderTableModel.addColumn("订单日期");
        orderTableModel.addColumn("总价");
        orderTableModel.addColumn("状态");

        orderTable = new JTable(orderTableModel);
        JScrollPane orderScrollPane = new JScrollPane(orderTable);
        add(orderScrollPane, BorderLayout.CENTER);

        deleteOrderButton = new JButton("删除选中的订单");
        deleteOrderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selectedRows = orderTable.getSelectedRows();
                if (selectedRows.length > 0) {
                    int selectedOption = JOptionPane.showConfirmDialog(OrderManagementPanel.this, "确定要删除选中的订单吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                    if (selectedOption == JOptionPane.YES_OPTION) {
                        try {
                            OrderDao orderDao = new OrderDao();
                            for (int row : selectedRows) {
                                int orderId = (int) orderTableModel.getValueAt(row, 0);
                                orderDao.deleteOrder(orderId);
                            }
                            loadOrders();
                        } catch (SQLException ex) {
                            JOptionPane.showMessageDialog(OrderManagementPanel.this, "删除订单失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            }
        });

        addOrderButton = new JButton("添加订单"); // 添加订单按钮
        addOrderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addOrder();
            }
        });

        editOrderButton = new JButton("编辑订单"); // 编辑订单按钮
        editOrderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editOrder();
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(deleteOrderButton);
        buttonPanel.add(addOrderButton);
        buttonPanel.add(editOrderButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public void loadOrders() {
        orderTableModel.setRowCount(0);
        try {
            OrderDao orderDao = new OrderDao();
            List<Order> orders = orderDao.getAllOrders();
            for (Order order : orders) {
                orderTableModel.addRow(new Object[]{order.getOrderId(), order.getUserId(), order.getOrderDate(), order.getTotalPrice(), order.getStatus()});
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载订单失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addOrder() {
        // 创建一个对话框来添加订单信息
        JFrame addOrderFrame = new JFrame("添加订单");
        addOrderFrame.setSize(400, 300);
        addOrderFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        addOrderFrame.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(5, 2));

        JLabel userIdLabel = new JLabel("用户ID:");
        JTextField userIdField = new JTextField(20);
        JLabel totalPriceLabel = new JLabel("总价:");
        JTextField totalPriceField = new JTextField(20);
        JLabel statusLabel = new JLabel("状态:");
        JTextField statusField = new JTextField(20);

        panel.add(userIdLabel);
        panel.add(userIdField);
        panel.add(totalPriceLabel);
        panel.add(totalPriceField);
        panel.add(statusLabel);
        panel.add(statusField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Order newOrder = new Order();
                newOrder.setUserId(Integer.parseInt(userIdField.getText()));
                newOrder.setTotalPrice(Double.parseDouble(totalPriceField.getText()));
                newOrder.setStatus(statusField.getText());

                OrderDao orderDao = new OrderDao();
                try {
                    orderDao.addOrder(newOrder);
                    addOrderFrame.dispose();
                    loadOrders();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(addOrderFrame, "添加订单失败", "错误", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });

        panel.add(saveButton);
        addOrderFrame.add(panel);
        addOrderFrame.setVisible(true);
    }

    private void editOrder() {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择一个订单进行编辑", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        int orderId = (int) orderTableModel.getValueAt(selectedRow, 0);
        int userId = (int) orderTableModel.getValueAt(selectedRow, 1);
        double totalPrice = (double) orderTableModel.getValueAt(selectedRow, 3);
        String status = (String) orderTableModel.getValueAt(selectedRow, 4);

        JFrame editOrderFrame = new JFrame("编辑订单");
        editOrderFrame.setSize(400, 300);
        editOrderFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        editOrderFrame.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(5, 2));

        JLabel userIdLabel = new JLabel("用户ID:");
        JTextField userIdField = new JTextField(String.valueOf(userId), 20);
        JLabel totalPriceLabel = new JLabel("总价:");
        JTextField totalPriceField = new JTextField(String.valueOf(totalPrice), 20);
        JLabel statusLabel = new JLabel("状态:");
        JTextField statusField = new JTextField(status, 20);

        panel.add(userIdLabel);
        panel.add(userIdField);
        panel.add(totalPriceLabel);
        panel.add(totalPriceField);
        panel.add(statusLabel);
        panel.add(statusField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Order updatedOrder = new Order();
                updatedOrder.setOrderId(orderId);
                updatedOrder.setUserId(Integer.parseInt(userIdField.getText()));
                updatedOrder.setTotalPrice(Double.parseDouble(totalPriceField.getText()));
                updatedOrder.setStatus(statusField.getText());

                OrderDao orderDao = new OrderDao();
                try {
                    orderDao.updateOrder(updatedOrder);
                    editOrderFrame.dispose();
                    loadOrders();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(editOrderFrame, "编辑订单失败", "错误", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });

        panel.add(saveButton);
        editOrderFrame.add(panel);
        editOrderFrame.setVisible(true);
    }
}
